package org.biubiu0002.baiblog.core.controller;

import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.common.constants.UserConstants;
import org.biubiu0002.baiblog.common.utils.R;
import org.biubiu0002.baiblog.core.annotations.PermissionIgnore;
import org.biubiu0002.baiblog.core.model.entity.SysUserEntity;
import org.biubiu0002.baiblog.core.model.vo.req.RegisterReqVo;
import org.biubiu0002.baiblog.core.model.vo.res.LoginResVo;
import org.biubiu0002.baiblog.core.model.vo.res.RegisterResVo;
import org.biubiu0002.baiblog.core.service.AuthService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-05 22:55
 **/
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @PermissionIgnore
    @PostMapping("/login")
    public R login(@RequestBody SysUserEntity sysUserEntity){
        Preconditions.checkArgument(StringUtils.isNotBlank(sysUserEntity.getUsername()),"用户名不能为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(sysUserEntity.getPassword()),"用户密码不能为空");
        LoginResVo loginResVo = authService.login(sysUserEntity);
        return R.ok().put("data",loginResVo);
    }

    @PermissionIgnore
    @PostMapping("/register")
    public R register(@RequestBody RegisterReqVo registerReqVo){
        Preconditions.checkArgument(StringUtils.isNotBlank(registerReqVo.getUsername()),"用户名不能为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(registerReqVo.getPassword()),"用户密码不能为空");
        Preconditions.checkArgument(registerReqVo.getUserType()!=null,"用户角色类型不能为空");
        if(registerReqVo.getUserType()== UserConstants.UserTypeEnum.ADMIN){
            Preconditions.checkArgument(StringUtils.isNotBlank(registerReqVo.getSecret()),"注册管理员的密钥不能为空");
        }
        RegisterResVo register = authService.register(registerReqVo);
        return R.ok().put("data",register);
    }

    /**
     * jwt的注销操作，注定没有比较好的解决方法，在社交网站微博场景，对注销后的权限控制要求不大，适当的泄露token权限也是可以接受的。
     * 需要前端清空token
     * @return 空操作
     */
    @PermissionIgnore
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        authService.logout(request);
        return R.ok();
    }

}
